#include "My_Socket.hpp"
#include <iostream>
#include <string>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
using namespace TcpServerModule;
using namespace LogModel;
using handler_t = std::function<void(HttpRequest &, HttpRespond &)>;
// 顶层 httpserver
// 中间层 tcpserver
// 下层 tcpsocket
// 下下层 socket
class HttpServer
{
public:
  HttpServer(int port) : _tscp(std::make_unique<TcpServer>(port))
  {
  }
  ~HttpServer()
  {
  }
  void Register(std::string funcname, handler_t func)
  {
    LOG(LogLevel::DEBUG)<<"进入路由注册"<<funcname;
    _route[funcname] = func;
  }
  void Start()
  {
    _tscp->InitSever([this](SockPtr sockfd, InetAdrr client)
                     { return this->HandlerHttpRequest(sockfd, client); });
    _tscp->Loop();
  }
  bool SafeCheck(std::string & service)
  {
    LOG(LogLevel::DEBUG)<<"进入安全检查";
    auto iter = _route.find(service);
    return iter!=_route.end();
  }
  void Print_Route()
  {
    LOG(LogLevel::DEBUG)<<"对路由进行检查";
    for(auto &e:_route)
    {
      LOG(LogLevel::DEBUG)<<e.first;
    }
  }
  bool HandlerHttpRequest(SockPtr sockfd, InetAdrr client)
  {
    // 这里的sockfd->Fd() 拿到的是经过Accept后的返回值 std::make_shared<TcpSocket>(newsockfd); 所以拿到的是客户端的sockfd
    LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << client.IP() << ": " << client.Port();
    std::string http_request;
    sockfd->Recv(&http_request);
    std::cout << http_request << std::endl;
    HttpRequest req;
    req.Deserialization(http_request);
    // req.Print();
    HttpRespond resp;
    if (req.IsHasArgs())
    {
      std::string service = req.Path();
      bool n = SafeCheck(service);
      Print_Route();
      LOG(LogLevel::DEBUG)<<n<<"安全检查结果"<<req.Path();
      if (n)
      {
        LOG(LogLevel::DEBUG)<<"进入路由";
        _route[req.Path()](req, resp); // /login
      }
      else
        resp.Build(req); // debug
    }
    else
    {
      resp.Build(req);
    }
    std::string resp_string;
    resp.Serialization(&resp_string);
    sockfd->Send(resp_string);

    // std::cout << http_request << std::endl; //字节流的请求
    //  读取请求，对请求进行分析处理 --> 文本处理！
    //  1. 读取请求的完整性 --- 暂时不做
    //  2. 完整http反序列化，http response序列化...
    //  demo 1 : 直接返回一个固定的内容
    //  std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine;

    // // 直接返回一个html网页
    // std::string body = "<!DOCTYPE html>\
        //                     <html>\
        //                    <head>\
        //                    <meta charset = \"UTF-8\">\
        //                    <title> Hello World</title>\
        //                    </head>\
        //                    <body>\
        //                    <p> wyt 是 傻呗</ p>\
        //                    </body> </html>";

    // std::string httpresponse = status_line + body;
    // sockfd->Send(httpresponse);
    return true;
  }

private:
  std::unique_ptr<TcpServer> _tscp;
  std::unordered_map<std::string, handler_t> _route;
};
